package com.shengde.jinwawaforleader.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseFragment;
import com.shengde.jinwawaforleader.base.CommonBaseAdapter;
import com.shengde.jinwawaforleader.base.ViewHolder;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.homePage.AttendanceActivity;
import com.shengde.jinwawaforleader.model.homePage.EveryConsultActivity;
import com.shengde.jinwawaforleader.model.homePage.HappyListActivity;
import com.shengde.jinwawaforleader.model.homePage.HotNewsMoreActivity;
import com.shengde.jinwawaforleader.model.homePage.InformationItemActivity;
import com.shengde.jinwawaforleader.model.homePage.SchoolMienActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProAttendanceList;
import com.shengde.jinwawaforleader.network.protocolbean.ProHotNewsList;
import com.shengde.jinwawaforleader.network.protocolbean.ProSchoolMiens;
import com.shengde.jinwawaforleader.utils.DateUtil;
import com.shengde.jinwawaforleader.views.MarqueenTextView;
import com.shengde.jinwawaforleader.views.MyChatView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页fragment
 */
public class HomePageFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "HomePageFragment";
    private static final int FINSH = 1;
    private static final int HOTNEWS = 2;
    private static final int SCHOOLMIEN = 3;
    private ListView lv_hotNews; //热门咨询的listview
    private MarqueenTextView tv_move_word;  //跑马灯
    private CommonBaseAdapter<ProHotNewsList.NewsBean> mHotNewsAdatpter;
    private TextView tv_back;  //返回按键
    private TextView tv_title; //title
    private TextView tv__total_num; //总人数
    private TextView tv_actual_num; //出勤 打卡的人数
    private TextView tv_leave_num; //请假人数
    private ProAttendanceList pro_attendance_list;
    private TextView tv_more; //更多的热门咨询
    private TextView tv_time; //打卡饼状图更新时间
    private TextView tv_array_already; //已到
    private TextView tv_array_no; //未到
    private TextView tv_request; //请假
    private List<ProHotNewsList.NewsBean> mNewsBean; //
    private List<ProHotNewsList.NoticeBean> mNoticeBean;
    private LinearLayout linear_mychatview;  // 饼状图布局
    private LinearLayout ll_all_person;  //全员应到
    private LinearLayout ll_actual_person;  //实际入园
    private LinearLayout ll_happy_person;  //请假人数
    private RelativeLayout relative_school_mien; //校园风采的背景图
    private ProSchoolMiens.SitelistEntity sitelistEntity;

    private MyChatView myChatView;  //记录出勤人数饼状图

    private ArrayList arrayList;  ////圆环数据 集合
    private ArrayList arrayList_person_num; //出勤人数比例


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FINSH:
                    int studentNum = pro_attendance_list.getSnum();
                    int teacherNum = pro_attendance_list.getTnum();
                    int noComeNum = pro_attendance_list.getKnum();
                    int questNum = pro_attendance_list.getQnum();
                    int totalNum = studentNum + teacherNum;
                    tv__total_num.setText(totalNum + "");
                    tv_actual_num.setText(noComeNum + "");
                    tv_leave_num.setText(questNum + "");
                    arrayList = new ArrayList();
                    arrayList_person_num = new ArrayList();
                    if (totalNum != 0) {
                        int a = (noComeNum * 100) / totalNum;
                        int b = (questNum * 100) / totalNum;
                        int c;
                        if (a == 0 && b == 0) {
                            c = 100;
                        } else {
                            c = 100 - a - b;
                        }
                        addPieData(c, b, a);
                    } else {
                        //如果班级没有人 那就是100%未到
                        addPieData(0, 100, 0);
                    }
                    break;
                case HOTNEWS:
                    mHotNewsAdatpter = new CommonBaseAdapter<ProHotNewsList.NewsBean>(acticity, mNewsBean, R.layout.index_school_item) {
                        @Override
                        public void convert(ViewHolder holder, int position) {
                            holder.setText(R.id.tv_school_item_title, mNewsBean.get(position).getTitle())
                                    .setText(R.id.tv_school_item_time, DateUtil.getDate(String.valueOf(mNewsBean.get(position).getLasttime())));
                            LinearLayout convertview = (LinearLayout) holder.getConvertView();
                            Glide.with(acticity)
                                    .load(BaseProtocol.IMG_BASE + mNewsBean.get(position).getPicturePath())
                                    .into((ImageView) convertview.findViewById(R.id.iv_school_item_logo));

                        }
                    };
                    lv_hotNews.setAdapter(mHotNewsAdatpter);
                    if (mNoticeBean.size() == 0) {
                        tv_move_word.setText("暂无公告");
                    } else {
                        tv_move_word.setText(mNoticeBean.get(0).getTitle());
                    }
                    break;
                case SCHOOLMIEN:
                    Glide.with(acticity).load(BaseProtocol.IMG_BASE + sitelistEntity.img)
                            .error(R.drawable.bg_school_mien)
                            .into(tv_bg_school_mien);
                    break;
            }
        }
    };
    private ImageView tv_bg_school_mien;


    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_home_page, null);
        initControl(view);
        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initControl(View view) {
        tv_move_word = (MarqueenTextView) view.findViewById(R.id.tv_move_word);
        lv_hotNews = (ListView) view.findViewById(R.id.lv_hotnews);
        tv_back = (TextView) view.findViewById(R.id.tv_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv__total_num = (TextView) view.findViewById(R.id.tv__total_num);
        tv_actual_num = (TextView) view.findViewById(R.id.tv_actual_num);
        tv_leave_num = (TextView) view.findViewById(R.id.tv_leave_num);
        tv_more = (TextView) view.findViewById(R.id.tv_more);
        tv_time = (TextView) view.findViewById(R.id.tv_time);
        tv_array_already = (TextView) view.findViewById(R.id.tv_array_already);
        tv_array_no = (TextView) view.findViewById(R.id.tv_array_no);
        tv_request = (TextView) view.findViewById(R.id.tv_request);
        ll_all_person = (LinearLayout) view.findViewById(R.id.ll_all_person);
        linear_mychatview = (LinearLayout) view.findViewById(R.id.linear_mychatview);
        ll_actual_person = (LinearLayout) view.findViewById(R.id.ll_actual_person);
        ll_happy_person = (LinearLayout) view.findViewById(R.id.ll_happy_person);
        myChatView = (MyChatView) view.findViewById(R.id.pie_chart_view);
        relative_school_mien = (RelativeLayout) view.findViewById(R.id.relative_school_mien);
        tv_bg_school_mien = (ImageView) view.findViewById(R.id.tv_bg_school_mien);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tv_back.setVisibility(View.INVISIBLE);
        tv_title.setText(User.getSchoolName(acticity));
        showSchoolMien();
        showAttendance();
        showHotNews();
        tv_time.setText(DateUtil.getDateMh(String.valueOf(System.currentTimeMillis())));

    }

    /**
     * 获取校园风采相关信息
     */
    private void showSchoolMien() {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/synopsis/synopsisList";
        } else {
            url = BaseProtocol.HOST_BASE + "/synopsis/synopsisList";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("schoolid", User.getSchoolId(acticity));
        Log.i(TAG, "onSuccess: schoolid = " + User.getSchoolId(acticity));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProSchoolMiens  proSchoolMiens = new Gson().fromJson(result, ProSchoolMiens.class);
                Log.i(TAG, "onSuccess: 78946");
                if (proSchoolMiens != null && proSchoolMiens.code == 0) {
                    Log.i(TAG, "onSuccess: schoolid = " + User.getSchoolId(acticity));
                    if (proSchoolMiens.sitelist.size()>0){
                        sitelistEntity = proSchoolMiens.sitelist.get(0);
                    mHandler.sendEmptyMessage(SCHOOLMIEN);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }


            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    @Override
    public void listener() {
        lv_hotNews.setOnItemClickListener(this);
        tv_more.setOnClickListener(this);
        tv_move_word.setOnClickListener(this);
        linear_mychatview.setOnClickListener(this);
        ll_all_person.setOnClickListener(this);
        ll_actual_person.setOnClickListener(this);
        ll_happy_person.setOnClickListener(this);
        relative_school_mien.setOnClickListener(this);
    }

    /**
     * 添加圆环数据的集合
     *
     * @param c
     * @param b
     * @param a
     */
    private void addPieData(int c, int b, int a) {
        //圆环数据
        arrayList.add(a);
        arrayList.add(c);
        arrayList.add(b);
        myChatView.setStrPercent(arrayList);
        //出勤人数比例
        tv_array_already.setText("已到人数 : " + a + "%");
        tv_array_no.setText("未到人数 : " + c + "%");
        tv_request.setText("请假人数 : " + b + "%");
        myChatView.invalidate();
    }

    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()) {
            case R.id.tv_more:
                Intent intent = new Intent(acticity, HotNewsMoreActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_move_word:  //跳转到公告列表界面
                intent = new Intent(acticity, EveryConsultActivity.class);
                startActivity(intent);
                break;
            case R.id.linear_mychatview:
            case R.id.ll_all_person:  //跳到考勤界面
            case R.id.ll_actual_person:
                intent = new Intent(acticity, AttendanceActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_happy_person: //跳转到请假人数界面
                intent = new Intent(acticity, HappyListActivity.class);
                startActivity(intent);
                break;
            case R.id.relative_school_mien:  //跳转到校园风采页面
                intent = new Intent(acticity, SchoolMienActivity.class);
                intent.putExtra("proSchoolMiens",sitelistEntity);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Intent intent = new Intent(acticity, InformationItemActivity.class);

        intent.putExtra("noticeId", mNewsBean.get(position)
                .getId() + "");
        intent.putExtra("noticeTitle", mNewsBean.get(position)
                .getTitle());
        intent.putExtra("imgpath", mNewsBean.get(position)
                .getPicturePath());
        startActivity(intent);
    }

    /**
     * 热门咨询和公告的 网络请求
     */
    private void showHotNews() {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/teacher/NewMessage";
        } else {
            url = BaseProtocol.HOST_BASE + "/teacher/NewMessage";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("schoolid", User.getSchoolId(acticity));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProHotNewsList pro_hot_news_list = new Gson().fromJson(result, ProHotNewsList.class);
                if (pro_hot_news_list != null && pro_hot_news_list.getCode() == 0) {
                    mNewsBean = pro_hot_news_list.getNews();
                    mNoticeBean = pro_hot_news_list.getNotice();
                    mHandler.sendEmptyMessage(HOTNEWS);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 首页考勤人数信息
     */
    public void showAttendance() {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/director/statisticsKq";
        } else {
            url = BaseProtocol.HOST_BASE + "/director/statisticsKq";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("schoolid", User.getSchoolId(acticity));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pro_attendance_list = new Gson().fromJson(result, ProAttendanceList.class);
                Log.i(TAG, "onSuccess: 78946");
                if (pro_attendance_list != null && pro_attendance_list.getCode() == 0) {
                    mHandler.sendEmptyMessage(FINSH);

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }


            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }
}